$(document).ready( function() {
	$(".gallery-viewer-style").each( function () {
		$thumbs = $(this).find(".gallery-item img");
		$(this).prepend("<div class='gallery-viewer'><img/></div>");
		$viewer = $(this).find(".gallery-viewer img");
		$viewer.attr('src', $thumbs.first().attr('src'));
		$viewer.attr('title', $thumbs.first().attr('title'));
		$thumbs.mouseover( function () {
			$viewer = $(this).parents(".gallery").find(".gallery-viewer img");
			$viewer.attr('src', $(this).attr('src'));
			$viewer.attr('title', $(this).attr('title'));
		});
	});
});

$(document).ready( function() {
	$(".gallery img").click( function () {
		setFrameImage( $(this) );
		$("#modal").show();
		return false; 
	});
	
	$("#modal #controls .close").click( function () {
		$("#modal").hide();
		return false;
	});
	
	$("#modal #controls .next").click( function () {
		$curr_item = getFrameCurrentItem();
		$next_item = $curr_item.next(".gallery-item");
		if ( $next_item.length == 0 ) {
			$next_item = $curr_item.siblings(".gallery-item").first();
		}
		setFrameImage( $next_item.find("img") );
		return false;
	});
	
	$("#modal #controls .prev").click( function () {
		$curr_item = getFrameCurrentItem();
		$prev_item = $curr_item.prev(".gallery-item");
		if ( $prev_item.length == 0 ) {
			$prev_item = $curr_item.siblings(".gallery-item").last();
		}
		setFrameImage( $prev_item.find("img") );
		return false;
	});
	
	$(window).resize( function () {
		resetFrameSize();
	});

	function getFrameCurrentItem () {
		image_src = $("#modal #frame img").attr('src');
		return $(".gallery .gallery-item").has('img[src='+image_src+']');
	}

	function setFrameImage ( $image ) {
		image_src = $image.attr('src');
		$("#modal #frame #content").html("<img src='" + image_src + "'/>");
		$("#modal #frame #caption").html( $image.attr('title') );
		resetFrameSize();
	}
	
	function resetFrameSize () {
		var winHeight = $(window).height();
		$("#modal").height(winHeight);
		
		var imgHeight = winHeight * 0.8;
		if ( imgHeight > 520 ) {
			imgHeight = 520;
		}
		$("#modal #frame #content img").height( imgHeight );
	}
});

$(document).ready( function () {
	$("img").bind("contextmenu", function(e){ return false; });
});
